package com.ruoyi.app.controller;

import java.util.concurrent.CountDownLatch;
import com.ruoyi.bizsys.domain.BatchJobMonitoring;
import com.ruoyi.bizsys.service.IBatchJobMonitoringService;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyThread implements Runnable {
	
    private String para3;
    private RedisCache redisCache;
    private IBatchJobMonitoringService batchDateJobService;
    private CountDownLatch countDownLatch;  //多线程结束后，执行后面的代码（计算时间、数量）
    
    public MyThread(RedisCache redisCache, IBatchJobMonitoringService batchDateJobService, String para3, CountDownLatch countDownLatch) {
        this.batchDateJobService = batchDateJobService;
        this.para3 = para3;
        this.redisCache = redisCache;
        this.countDownLatch = countDownLatch;
    }
    
    private void runTest() {
    	
	        	BatchJobMonitoring batchJobMonitoring = batchDateJobService.selectBatchJobMonitoringById((long) 1);
	        	int aa = Integer.parseInt(batchJobMonitoring.getResultDesc());
	        	log.info(para3 + "=========="+"消费前库存为"+aa);
	        	
	        	aa=aa-1;
	        	batchJobMonitoring.setResultDesc(aa+"");
	        	batchDateJobService.updateBatchJobMonitoring(batchJobMonitoring);
	        	
	        	batchJobMonitoring = batchDateJobService.selectBatchJobMonitoringById((long) 1);
	        	aa = Integer.parseInt(batchJobMonitoring.getResultDesc());
	        	log.info(para3 + "=========="+"消费后仓库结余库存为"+aa);
        	
        
    }

    public void run() {
    	String lockKey = "testKey";
    	try{

        	for(int i=0;i<10;i++) {

        		int j = 0;
        		while(j<5) {
        			//j++;
        			// 设置全局锁ID uuid就行
					String lockValue = IdUtils.fastSimpleUUID();
			    	boolean lock = redisCache.lock(lockKey,lockValue);
					if(lock) {
						 try {
							 this.runTest();
						 } finally {
							 //释放锁
							 redisCache.unLock(lockKey,lockValue);
						 }
						 break;
					} else {
						 //new RuntimeException("重复领取奖励");
						log.info(para3 + "=========="+"系统繁忙。。。。。。。。。。。。。。");
						Thread.sleep(1000);
					}
        		}
				
        	}

        	
    	}catch(Exception e){
            e.printStackTrace();
        }finally {
            countDownLatch.countDown();
        }

    }

}